package com.itheima.demo05;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CountDownLatch;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/7/14 21:06
 */
/*
        URL url = new URL("图片地址");
        URLConnection conn = url.openConnection();
        InputStream in = conn.getInputStream();
 */
public class MyRunnable002 implements Runnable {
    private String path;
    private CountDownLatch cd;

    public MyRunnable002(String path,CountDownLatch cd) {
        this.path = path;
        this.cd = cd;
    }

    @Override
    public void run() {
        URL url = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            url = new URL(path);
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();
            File file = new File(path);
            String name = file.getName();
            bis = new BufferedInputStream(in);
            bos = new BufferedOutputStream(new FileOutputStream
                    ("E:\\cccc\\" + name));
            //读写数据;
            byte[] arr = new byte[1024 * 8];
            int len;
            while ((len = bis.read(arr)) != -1) {
                bos.write(arr, 0, len);
                bos.flush();
            }
            //等待线程执行完毕!
            cd.countDown();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
